package com.lin.filegraph.utils.parser.astvisitor;

import com.lin.filegraph.utils.parser.node.JFieldNode;
import com.lin.filegraph.utils.parser.node.JTypeNode;
import org.eclipse.jdt.core.dom.*;

import java.lang.reflect.Modifier;
import java.util.List;

/**
 * @description:
 * @author: linhuaixu
 * @time: 2023/5/18 14:10
 */

public class FieldVisitor {

    private JTypeNode typeNode;

    public FieldVisitor(JTypeNode typeNode) {
        this.typeNode = typeNode;
    }

    public void visit(FieldDeclaration node) {
        List fragments = node.fragments();
        for (Object fragment : fragments) {
            if (fragment instanceof VariableDeclarationFragment) {
                VariableDeclarationFragment field = (VariableDeclarationFragment) fragment;
                if (field.resolveBinding() != null) {
                    String fieldName = field.getName().toString();
                    String returnType = field.resolveBinding().getType().getBinaryName();
                    String modifier = Modifier.toString(field.resolveBinding().getModifiers());
                    JFieldNode fieldNode = new JFieldNode(typeNode.getFilePath(), node, fieldName, returnType,
                            modifier);
                    typeNode.addChildNode(fieldNode);
                }
            }
        }
    }

    public void traverseFields() {
        if (typeNode.getAstNode() instanceof TypeDeclaration) {
            TypeDeclaration typeDeclaration = (TypeDeclaration) typeNode.getAstNode();
            for (Object bodyDeclaration : typeDeclaration.bodyDeclarations()) {
                if (bodyDeclaration instanceof FieldDeclaration) {
                    visit((FieldDeclaration) bodyDeclaration);
                }
            }
        }
        if (typeNode.getAstNode() instanceof AnonymousClassDeclaration) {
            AnonymousClassDeclaration anonymousClassDeclaration = (AnonymousClassDeclaration) typeNode.getAstNode();
            for (Object bodyDeclaration : anonymousClassDeclaration.bodyDeclarations()) {
                if (bodyDeclaration instanceof FieldDeclaration) {
                    visit((FieldDeclaration) bodyDeclaration);
                }
            }
        }
        if (typeNode.getAstNode() instanceof EnumDeclaration) {
            EnumDeclaration enumDeclaration = (EnumDeclaration) typeNode.getAstNode();
            for (Object bodyDeclaration : enumDeclaration.bodyDeclarations()) {
                if (bodyDeclaration instanceof FieldDeclaration) {
                    visit((FieldDeclaration) bodyDeclaration);
                }
            }
        }
    }
}

